//
//  SecondViewController.m
//  MallTest2
//
//  Created by peng liu on 2018/9/1.
//  Copyright © 2018年 lxiaod. All rights reserved.
//

#import "SecondViewController.h"
#import "ItemTableViewCell.h"
#import "HttpUtils.h"
#import "ItemCollectionViewCell.h"
#import "ItemDetailViewController.h"

@interface SecondViewController ()<UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource>
{
    NSMutableArray *typeArray;
    NSMutableArray<NSMutableArray *> *detailArray;
    NSMutableArray *typeListArray;
}
@property (weak, nonatomic) IBOutlet UINavigationItem *nav;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@end

@implementation SecondViewController

static NSString *itemIndetifler = @"itemcell";
static NSString *collIndetifler = @"itemCollCell";
static NSString *collDetailsHeadID = @"leaveDetailsHeadID";
static NSString *collDetailsFooterID = @"leaveDetailsFooterID";

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"分类";
    typeArray =[NSMutableArray array];
    detailArray =[NSMutableArray array];
    typeListArray = [NSMutableArray array];
    
    _collectionView.showsHorizontalScrollIndicator=NO;
    _collectionView.showsVerticalScrollIndicator=NO;
    //注册collection cell
    [_collectionView registerNib:[UINib nibWithNibName:@"ItemCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:collIndetifler];
    //注册headview
    [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:collDetailsHeadID];
    //注册footerview
    [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:collDetailsFooterID];
    
    [HttpUtils getDataList:@"item/type" success:^(NSData * data) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            // 处理耗时操作的代码块...
            id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            self->typeArray = (NSMutableArray *) jsonObject;
            //通知主线程刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"%@",self->typeArray);
                
                [self.tableView reloadData];
                //默认选中第一行
                NSIndexPath * selIndex = [NSIndexPath indexPathForRow:0 inSection:0];
                [self.tableView selectRowAtIndexPath:selIndex animated:YES scrollPosition:UITableViewScrollPositionTop];
            });
        });
    }];
    
    [self getCollectionViewData:@"0"];
}


//tableview加载
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ItemTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:itemIndetifler];
    
    if(cell == nil){
        //使用代码创建
        //cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle //reuseIdentifier:indet];
        //使用nib创建
        cell = [[NSBundle mainBundle] loadNibNamed:@"ItemTableViewCell" owner:nil options:nil][0];
    }
    NSDictionary *data = [typeArray objectAtIndex:indexPath.row];
    cell.lable.text=[data objectForKey:@"name"];
    cell.dataId = [data objectForKey:@"id"];
    return cell;
}

//cell数量
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return typeArray.count;
}

//行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

//点击选择的cell
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ItemTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [self getCollectionViewData:cell.dataId];
}

//collectionView 多少个cellcell
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
   return [detailArray[section] count];
}

//每个cell显示什么
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ItemCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:collIndetifler forIndexPath:indexPath];
    
    //NSDictionary *data = [detailArray objectAtIndex:indexPath.row];
     NSDictionary *data = [[detailArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    cell.label.text=[data objectForKey:@"name"];
    cell.dataId = [data objectForKey:@"id"];
    
    NSString *imgurl =[data objectForKey:@"img"];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSURL *photourl = [NSURL URLWithString:imgurl];
        //url请求实在UI主线程中进行的
        UIImage *images = [UIImage imageWithData:[NSData dataWithContentsOfURL:photourl]];
        //通知主线程刷新
        dispatch_async(dispatch_get_main_queue(), ^{
            cell.imgView.image =images;
        });
    });
    return cell;
}

//有多少个sections
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return typeListArray.count;
}

//cell的header与footer的显示内容
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionHeader)
    {
        UICollectionReusableView *reusableHeaderView = nil;
        if (reusableHeaderView==nil) {
            reusableHeaderView = [_collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader  withReuseIdentifier:collDetailsHeadID forIndexPath:indexPath];
            reusableHeaderView.backgroundColor = [UIColor whiteColor];
            
            //这部分一定要这样写 ，否则会重影，不然就自定义headview
            UILabel *label = (UILabel *)[reusableHeaderView viewWithTag:100];
            if (!label) {
                label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, self.view.frame.size.width, 30)];
                label.tag = 100;
                [reusableHeaderView addSubview:label];
            }
            label.text = typeListArray[indexPath.section];
        }
        return reusableHeaderView;
        
    }else if (kind == UICollectionElementKindSectionFooter){
        
        UICollectionReusableView *reusableFooterView = nil;
        if (reusableFooterView == nil) {
            reusableFooterView = [_collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter  withReuseIdentifier:collDetailsFooterID forIndexPath:indexPath];
            reusableFooterView.backgroundColor = [UIColor colorWithRed:((float)232/255) green:((float)232/255) blue:((float)232/255) alpha:0.8f];
        }
        
        return reusableFooterView;
    }
    return nil;
}

//点击collection
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    //ItemDetailViewController *cont = [[ItemDetailViewController alloc]init];
    //[self.navigationController pushViewController:cont animated:YES];
    NSDictionary *data = [[detailArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    [self performSegueWithIdentifier:@"detailPushIdentifer" sender:data];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)getCollectionViewData:(NSString *)typeId{
    NSString *url = [NSString stringWithFormat:@"item/detail?typeid=%@",typeId];
    [HttpUtils getDataList:url success:^(NSData * data) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            // 处理耗时操作的代码块...
            id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            //self->detailArray = (NSMutableArray *) jsonObject;
            
            NSDictionary *datas = (NSDictionary *) jsonObject;
            NSMutableArray *typArr = [datas objectForKey:@"typeArr"];
            NSDictionary *dataDic = [datas objectForKey:@"dataDic"];
            
            [self->detailArray removeAllObjects];
            for(int i=0 ;i<typArr.count;i++){
                NSString *typeName = typArr[i];
                NSMutableArray *arr = [dataDic objectForKey:typeName];
                [self->detailArray addObject:arr];
            }
            self->typeListArray =typArr;
            NSLog(@"%@",typArr);
            NSLog(@"%@",self->detailArray);
            //通知主线程刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                //[self.collectionView reloadSections:nil];
                [self.collectionView reloadData];
            });
        });
    }];
}

//页面跳转
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if([segue.identifier isEqualToString:@"detailPushIdentifer"]){
        ItemDetailViewController *cont =segue.destinationViewController;
        NSLog(@"%@",sender);
        NSDictionary *data  = sender;
        cont.name = [data objectForKey:@"name"];
        cont.idnum =[NSString stringWithFormat:@"%@",[data objectForKey:@"id"]];
    }
}
@end
